from querier.esquerier import ElasticSearchQuerier
import json

WORDCLOUD_TOP_N = 100


class WechatContentTypeTagsQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type):
        super(WechatContentTypeTagsQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args.get('biz_code')
        if not id_:
            return {'message': 'biz_code is needed'}

        res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        if res['found']:
            res = json.loads(res['_source']['content_type'].replace("'", '"'))
            # res = [(x, x['weight']) for x in res]
            # res = sorted(res, key=operator.itemgetter(1), reverse=True)
            # res = [x[0] for x in res[:WORDCLOUD_TOP_N]]

            keys = ['text', 'image', 'video']
            ratio = [res.get(x, 0.0) for x in keys]
            s = sum(ratio)
            prob = [x / s for x in ratio]

            out = zip(keys, prob)

            ret2 = [{"text": k[0], "weight": k[1]} for k in out]
            return {'tags': ret2}

        return {'message': 'biz_code=%s not found.' % id_}

    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass
